# -*- coding: utf-8 -*-

import __main__
from appengine_utilities import sessions
from appengine_utilities import flash
from appengine_utilities import event
from appengine_utilities import cache
from appengine_utilities.rotmodel import ROTModel

import wsgiref.handlers
import xmw
from xmw.db import ds
from google.appengine.ext import webapp
from google.appengine.ext import db
import urllib

import logging
from xmw.db import user_mgr


def login(sess,mail,passwd):
    user= user_mgr.get_user_by_mail(mail)
    if user is None:
        return None
    if user.password != passwd:
        return None
    sess["user"] = ds.XMW_Session_User(name =user.name,email=user.email,user_id=user.user_id)
    sess["user"].put()
    return user

class MainPage(xmw.RequestHandler):
    def get(self):
        self.sess = sessions.Session()
        self.cookie_sess = sessions.Session(writer="cookie")          
        session_user =None
        if self.sess.has_key("user"):
            session_user=self.sess["user"]
        logging.log( logging.INFO, "session_user :%s"%str(session_user))
        template_values ={"session_user":session_user,"wrong_passwd":False}
        #template_values={"wrong_passwd":False}        
        self.render_template(template_values, "../html/login.html")
        return
    
    def post(self):
        self.sess = sessions.Session()
        self.cookie_sess = sessions.Session(writer="cookie")
         
        if not ( self.request.POST.has_key('form_email') and self.request.POST.has_key('form_password')):
            self.response.out.write("user_mail & password missed")
            return
        
        form_email  =   self.request.POST['form_email']
        form_password  =   self.request.POST['form_password']
        form_email  =form_email.strip().decode('utf-8')
        form_password  =form_password.strip().decode('utf-8')
        #print form_email
        #print form_password.decode('utf-8')
        #logging.log( logging.INFO, "email %s,and password %s"% (form_email,form_password))
        if len(form_password) == 0 or len(form_email) == 0:
            self.response.out.write("user_mail & password missed")
            return
        
        """
        user= user_mgr.get_user_by_mail(form_email)
        if user is None:
            template_values={"wrong_passwd":True,
                             "form_email":form_email}         
            self.render_template(template_values, "../html/login.html")
            #self.response.out.write("user/passwd error")
            return
        if user.password != form_password:
            template_values={"wrong_passwd":True,
                             "form_email":form_email}        
            self.render_template(template_values, "../html/login.html")
            
            #self.response.out.write("password error")
            return
        
        
        #self.cookie_sess
        #self.response.out.write("user login %s"%user.name)
        #now login ok
        
                   
        self.sess["user"] = ds.XMW_Session_User(name =user.name,email=user.email)
        self.sess["user"].put()
        """
        user=login(self.sess,form_email,form_password)
        if user is None:
            template_values={"wrong_passwd":True,
                             "form_email":form_email}         
            self.render_template(template_values, "../html/login.html")
            #self.response.out.write("user/passwd error")
            return
        
        login_action =None
        
        if self.sess.has_key("login_action"):
            login_action=self.sess["login_action"]
            logging.log( logging.INFO, "login_action %s"% login_action.action)
            template_values={"login_action":login_action,}        
            #self.render_template(template_values, "../html/"+login_action.action+".html")
            self.redirect(login_action.action+"?"+login_action.params.encode("utf-8"))
            self.sess["login_action"].delete()
            return
        self.redirect("/")
        
def main():
  application = webapp.WSGIApplication(
                                       [('/login', MainPage)],
                                       debug=True)
  wsgiref.handlers.CGIHandler().run(application)

if __name__ == "__main__":
  main()